import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import { useCourses, useDeleteCourse } from '@/services/course';
import { ICourse } from '@/utils/types';
import { DEFAULT_PAGE_SIZE } from '@/utils/constance';
import { Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useRef, useState } from 'react';
import { getColumns } from './constants';
import EditCourse from './components/EditCourse';
import OrderTime from './components/OrderTime';
import ConsumerCard from './components/ConsumerCard';

/**
* 课程管理页面
*/
const Course = () => {
  const actionRef = useRef<ActionType>();
  const { refetch } = useCourses();
  const [curId, setCurId] = useState('');
  const [showInfo, setShowInfo] = useState(false);
  const onClickAddHandler = (id?: string) => {
    if (id) {
      setCurId(id);
    } else {
      setCurId('');
    }
    setShowInfo(true);
  };
  const closeAndRefetchHandler = (isReload?: boolean) => {
    setShowInfo(false);
    if (isReload) {
      actionRef.current?.reload();
    }
  };
  // 可约时间
  const [showOrderTime, setShowOrderTime] = useState(false);
  const onOrderTimeHandler = (id: string) => {
    setCurId(id);
    setShowOrderTime(true);
  };
  // 管理消费卡
  const [showCard, setShowCard] = useState(false);
  const onCardHandler = (id: string) => {
    setCurId(id);
    setShowCard(true);
  };
  // 删除
  const [delHandler] = useDeleteCourse();
  const onClickDelHandler = (id: string) => {
    delHandler(id, closeAndRefetchHandler);
  };

  return (
    <PageContainer header={{ title: '当前门店下开设的课程' }}>
      {/* ICourse这个类型和columns是相对应的 */}
      <ProTable<ICourse>
        rowKey="id"
        actionRef={actionRef} // 用于去调用当前实例的一些方法，如刷新
        columns={getColumns({
          onEditHandler: onClickAddHandler,
          onOrderTimeHandler,
          onCardHandler,
          onDelHandler: onClickDelHandler,
        })}
        pagination={{
          pageSize: DEFAULT_PAGE_SIZE,
        }}
        // 右上角（添加新建按钮）
        toolBarRender={() => [
          <Button type="primary" onClick={() => onClickAddHandler()} key="add" icon={<PlusOutlined />}>新建</Button>,
        ]}
        // request用于检索
        request={refetch}
      />
      {/* 编辑课程抽屉 */}
      { showInfo && <EditCourse id={curId} onClose={closeAndRefetchHandler} /> }
      {/* 编辑可约时间抽屉 */}
      { showOrderTime && <OrderTime id={curId} onClose={() => setShowOrderTime(false)} /> }
      {/* 编辑关联消费卡 */}
      { showCard && <ConsumerCard id={curId} onClose={() => setShowCard(false)} /> }
    </PageContainer>
  );
};

export default Course;
